# -*- coding: UTF-8 -*-
#python 2.7.*: email.Utils email.Encoders
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE,formatdate
from email import encoders
import os

'''
发送邮件
    server：服务器设置，格式server['name'], server['user'], server['passwd']
    fro:发送方
    to:送达方
    subject:主题
    text:文本
    cc:抄送
    files:附件
'''
def send_mail(server, fro, to, subject, text, cc=[], files=[]): 
    assert type(server) == dict 
    assert type(to) == list
    assert type(cc) == list 
    assert type(files) == list 
 
    msg = MIMEMultipart()
    
    msg['From'] = fro 
    msg['Subject'] = subject 
    msg['To'] = COMMASPACE.join(to) #COMMASPACE==', '
    msg['Cc'] = COMMASPACE.join(cc)
    msg['Date'] = formatdate(localtime=True) 
    msg.attach(MIMEText(text)) 
    
    #附件
    for f in files: 
        part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data 
        part.set_payload(open(f, 'rb').read())
        encoders.encode_base64(part) 
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) 
        msg.attach(part) 

    #发送邮件
    import smtplib
    smtp = smtplib.SMTP(server['name']) 
    smtp.login(server['user'], server['passwd']) 
    smtp.sendmail(fro, to, msg.as_string()) 
    smtp.close()
    
if __name__ =="__main__":
    #send_mail(server, fro, to, subject, text, files=[]): 
    server={'name':'smtp.basechina.net','user':'wangxingxiang@basechina.net','passwd':'wangxingxiang'} 
    to=['wxxlily@gmail.com']
    cc=['352020897@qq.com']
    files=['d:\\JPushExample(117783).zip']
    send_mail(server,
              'wangxingxiang@basechina.net',
              to,
              'test send mail',
              'test send mail',
              cc,
              files)
    print 'sended'